<!-- <template>
    <div>
        <input type="file" @change="handleFileChange">
        <button @click="uploadImage">上传图片</button>
        <img :src="imageUrl" v-if="imageUrl" style="max-width: 300px;">
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectedFile: null,  // 是一个file类型的文件对象，用于保存图片文件的信息，发送到后端
            imageUrl: null       // 是图片的URL地址，用于回显图片
        };
    },
    methods: {
        // 用户点击上传图片后，保存图片文件的信息和URL地址
        handleFileChange(event) {
            this.selectedFile = event.target.files[0];
            this.imageUrl = URL.createObjectURL(this.selectedFile);
        },
        // 将数据提交到后台
        uploadImage() {
            const formData = new FormData();
            formData.append('image', this.selectedFile);  // 向后端请求的数据是file对象
            // 向后端发送请求
            fetch('/upload', {
                method: 'POST',
                body: formData
            }).then(() => { });
        }
    }
}
</script> -->
<template>
    <div>
        <el-upload class="avatar-uploader" :on-change="handleChange" action="" :show-file-list="false"
            :auto-upload="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<script>
export default {
    data() {
        return {
            imageUrl: ''
        };
    },
    methods: {
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        handleChange(file, fileList) {
            console.log(fileList);

            if (file.raw) {
                this.imageUrl = URL.createObjectURL(file.raw);
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>